#ifdef GL_FRAGMENT_PRECISION_HIGH
	precision highp float;
#else
	precision mediump float;
#endif

uniform lowp sampler2D	textureSampler;
uniform lowp sampler2D	normalsSampler;

uniform float			specularPower;		// eg 30.0
uniform lowp vec3		diffuseColor;		// eg 0.21, 0.21, 0.21
uniform lowp vec3		specularColor;		// eg 0.5, 0.5, 0.5
uniform lowp vec3		fresnelColor;		// eg 0.35, 0.35, 0.7
uniform float			ambientAmount;		// eg 0.35

varying vec2			texCoords;
varying	vec3			tangentLight;
varying	vec3			tangentView;
varying vec3			tangentToWorldY;

//varying	float	selfShadow;

void main()
{

	vec3	tLight			= normalize(tangentLight);
	vec3	tView			= normalize(tangentView);

	// lookup normal
	vec3	nSample			= normalize(texture2D(normalsSampler, texCoords).rgb - 0.5);
	
	// compute diffuse term
	float	kd				= max(0.0, dot(tLight, nSample));
	
	// compute specular term
	vec3	halfV			= normalize(tLight - tView);
	float	ndotHalfV		= max(dot(nSample, halfV), 0.0);
	float	ks				= pow(ndotHalfV, specularPower);

	// compute reflected y direction in world space
	float ry				= dot(tangentToWorldY, reflect(tView, nSample));
	float rl				= fract(-ry);

	// compute fresnel term
	float viewDotSample		= dot(tView, nSample);
	float c					= min(viewDotSample, 0.0);	
	float kf				= pow( 1.0 + c, 3.0);	

	// lookup texture
	lowp vec3 textureSample = texture2D(textureSampler, texCoords).rgb ;

	// compute components of lighting equation
	lowp vec3 cd			= (kd * diffuseColor + vec3(ambientAmount)) * textureSample;
	lowp vec3 cs			= (/*selfShadow * */ ks)					* specularColor;
	lowp vec3 cf			= (rl * kf)									* fresnelColor;
	
	// compute final color
	gl_FragColor = vec4( cd + cs + cf, 1.0 );

}